<?php

namespace app\common\model\order;

use addons\epay\library\Service;
use app\api\model\Gold;
use think\Db;
use think\Exception;
use think\Model;


class Pay extends Model
{


    // 表名
    protected $name = 'order_pay';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'pay_time_text'
    ];


    public function getPayTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_time']) ? $data['pay_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPayTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public static function pay($params)
    {
        extract($params);
        $pay_info = Gold::get($id);
        if (!$pay_info || $pay_info['is_show'] != 1) {
            throw new Exception("当前金币选项已关闭");
        }

        $order_sn = order_sn();
        $data = [
            'user_id' => $user_id,
            'order_sn' => $order_sn,
            'money' => $pay_info['money'],
            'price' => $pay_info['price']
        ];
        $order_pay = self::create($data);
        return $order_pay;
    }


    public static function pay_error($id, $params)
    {
        return self::update($params, ['id' => $id]);
    }

    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
